<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        placeholder="搜索内容"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select
        v-model="listQuery.importance"
        placeholder="基础信息查询"
        clearable
        style="width: 130px"
        class="filter-item"
      >
        <el-option
          v-for="item in importanceOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-cascader
        v-model="listQuery.area"
        :options="options"
        placeholder="按区域查询"
        :separator="'/'"
        class="filter-item"
        @change="handleChangeforSeah"
      />
      <el-select
        v-model="listQuery.sort"
        style="width: 140px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="item in sortOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >新增</el-button>
      <el-button
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >下载表格</el-button>
      <el-checkbox
        v-model="showReviewer"
        class="filter-item"
        style="margin-left:15px;"
        @change="tableKey=tableKey+1"
      >显示用户id</el-checkbox>
      <el-button
        class="filter-item"
        style="margin-left:15px;"
        type="primary"
        @click="showAll"
      >显示全部用户</el-button>
    </div>
    <!-- ==============表格========================= -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        v-if="showReviewer"
        label="ID"
        prop="_id"
        sortable="custom"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{row}">
          <span>{{ row._id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" width="110px">
        <template slot-scope="{row}">
          <span style="color:red;">{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="昵称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="真实姓名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.truename }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货地址" min-width="150px">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所在区域" align="center">
        <template slot-scope="{row}">
          <span>{{ row.area }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Vip等级" align="center">
        <template slot-scope="{row}">
          <svg-icon v-for="n in + row.vip" :key="n" icon-class="star" class="meta-item__icon" />
        </template>
      </el-table-column>
      <el-table-column label="积分" align="center">
        <template slot-scope="{row}">
          <span
            v-if="row.pageviews"
            class="link-type"
            @click="handleFetchPv(row.pageviews)"
          >{{ row.integrate }}</span>
          <span v-else>0</span>
        </template>
      </el-table-column>
      <el-table-column label="账户状态" class-name="status-col">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">{{ row.status?"正常":"封禁" }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="Actions"
        align="center"
        width="300"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">修改</el-button>
          <el-button
            v-if="row.status"
            size="mini"
            type="success"
            @click="handleModifyStatus(row,0)"
          >封禁</el-button>
          <el-button v-if="!row.status" size="mini" @click="handleModifyStatus(row,1)">解封</el-button>
          <el-button
            v-if="row.status!='deleted'"
            size="mini"
            type="danger"
            @click="handleDelete(row,$index)"
          >删除</el-button>
          <el-button size="mini" type="info" @click="handlePit(row)">宠物</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- =====================翻页 ====================-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!--==================== 表单 ================-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="手机号" prop="phone">
          <el-input v-model.number="temp.phone" maxlength="11" />
        </el-form-item>
        <el-form-item label="昵称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="truename">
          <el-input v-model="temp.truename" />
        </el-form-item>
        <el-form-item label="积分">
          <el-input v-model="temp.integrate" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio v-model="temp.status" label="1">正常</el-radio>
          <el-radio v-model="temp.status" label="0">封禁</el-radio>
          <span>（默认选择正常）</span>
        </el-form-item>
        <el-form-item label="VIP等级" prop="vip">
          <el-rate
            v-model="temp.vip"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
            :max="5"
            style="margin-top:8px;"
          />
        </el-form-item>
        <el-form-item label="收货地址" prop="address">
          <el-input
            v-model="temp.address"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="请输入正确的收货地址"
          />
        </el-form-item>
        <el-form-item label="区域">
          <el-cascader
            v-model="selectedOptions"
            :options="options"
            :separator="' '"
            @change="handleChange"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">Cancel</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
    <!-- ======= 宠物表格 ==================-->
    <el-dialog :title="petTitle" :visible.sync="dialogTableVisible">
      <el-table v-if="hasPet" :data="petData">
        <el-table-column property="name" label="爱宠姓名" width="150" />
        <el-table-column property="age" label="爱宠年龄" width="200" />
        <el-table-column property="color" label="爱宠颜色" />
        <el-table-column property="nature" label="爱宠性格" />
        <el-table-column property="type" label="爱宠品种" />
      </el-table>
      <el-form v-else-if="!hasPet" :model="form" style="width: 400px; margin-left:50px;">
        <el-form-item label="爱宠姓名:" label-width="120px">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="爱宠年龄:" label-width="120px">
          <el-input v-model="form.age" />
        </el-form-item>
        <el-form-item label="爱宠颜色:" label-width="120px">
          <el-input v-model="form.color" />
        </el-form-item>
        <el-form-item label="爱宠性格:" label-width="120px">
          <el-input v-model="form.nature" />
        </el-form-item>
        <el-form-item label="爱宠品种:" label-width="120px">
          <el-input v-model="form.type" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="AddPet">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  fetchPv,
  createArticle,
  updateArticle
} from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import options from '../../utils/country-data.js'
import {
  creatPetUser,
  getAllPetuser,
  petuserUpdate,
  deletePetUser
} from '@/api/admin'
const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      form: {
        name: '',
        age: '',
        color: '',
        nature: '',
        type: ''
      },
      petTitle: '',
      hasPet: false,
      selectedOptions: [], // 存放默认值
      options: options, // 存放城市数据
      dialogTableVisible: false,
      nowuser: {},
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        area: undefined,
        title: undefined,
        importance: undefined,
        type: {},
        sort: -1
      },
      importanceOptions: [
        { label: '电话', value: 'phone' },
        { label: '真实姓名', value: 'truename' },
        { label: '昵称', value: 'name' }
      ],
      calendarTypeOptions,
      sortOptions: [
        { label: '最早加入成员', key: +1 },
        { label: '近期加入成员', key: -1 }
      ],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        phone: 1,
        name: '',
        truename: '',
        vip: 1,
        address: '',
        area: '',
        status: 1,
        integrate: '0'
      },
      petData: [],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        phone: [
          { required: true, message: '请争取输入手机号', trigger: 'change' }
        ],
        name: [
          {
            required: true,
            message: '请输入昵称',
            trigger: 'change'
          }
        ],
        truename: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getAllPetuser(this.listQuery).then(res => {
        this.list = res.data.items
        this.total = res.data.title
      })

      // Just to simulate the time of the request
      setTimeout(() => {
        this.listLoading = false
      }, 1000)
    },
    // 新增宠物
    AddPet() {
      this.dialogTableVisible = false
      this.nowuser.pet = [this.form]
      petuserUpdate(this.nowuser).then(res => {
        if (res.data._id) {
          this.$notify({
            title: '成功',
            message: '成功增加宠物',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    handleChangeforSeah() {
      this.listQuery.type = {
        area: this.listQuery.area.join('')
      }
    },
    handleChange(value) {
      this.selectedOptions = value
    },
    handlePit(row) {
      this.nowuser = row
      if (row.pet.length) {
        this.hasPet = true
        this.petTitle = '宠物列表'
        this.petData = row.pet
      } else {
        this.petTitle = '新增宠物'
        this.hasPet = false
        this.$message({
          type: 'info',
          message: '还没有宠物，添加一个'
        })
      }
      this.dialogTableVisible = true
    },

    showAll() {
      this.listQuery = {
        page: 1,
        limit: 10,
        area: undefined,
        title: undefined,
        importance: undefined,
        type: {},
        sort: -1
      }
      this.getList()
    },
    handleFilter() {
      if (importance == 'phone') {
        this.listQuery.title = parseInt(this.listQuery.title)
      }
      const { importance, title, area } = this.listQuery
      if (area) {
        this.listQuery.type = {
          area: area.join('')
        }
      }
      this.listQuery.type[importance] = title

      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      row.status = status
      petuserUpdate(row).then(res => {
        this.$message({
          message: '操作Success',
          type: 'success'
        })
      })
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        phone: undefined,
        name: '',
        truename: '',
        vip: undefined,
        address: '',
        area: '',
        status: 1,
        integrate: '0'
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(async valid => {
        if (valid) {
          if (this.selectedOptions.length) {
            this.temp.area = this.selectedOptions.join('')
            const res = await creatPetUser(this.temp)
            if (res._id) {
              // this.list.unshift(this.temp);
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '成功增加一位新宠主',
                type: 'success',
                duration: 2000
              })
            }
            this.getList()
          }
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)

          petuserUpdate(this.temp).then(res => {
            if (res.data._id) {
              const index = this.list.findIndex(v => v.id === this.temp.id)
              this.dialogFormVisible = false
              this.list.splice(index, 1, this.temp)
              this.$notify({
                title: '成功',
                message: '恭喜您，修改成功',
                type: 'success',
                duration: 1500
              })
            }
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deletePetUser(row._id).then(res => {
            if (res.data.ok) {
              this.$notify({
                title: '成功',
                message: '已成功删除',
                type: 'success',
                duration: 1000
              })
              this.list.splice(index, 1)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          'phone',
          'name',
          'truename',
          'vip',
          'address',
          'area',
          'status',
          'integrate'
        ]
        const filterVal = [
          'phone',
          'name',
          'truename',
          'vip',
          'address',
          'area',
          'status',
          'integrate'
        ]
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style scoped>
</style>
